const api = require('../../../utils/api')
const config = require('../../../utils/config')

Page({
  data: {
    orderId: null,
    orderInfo: null,
    loading: true,
    statusMap: {
      0: '待支付',
      1: '待发货',
      2: '待收货',
      3: '已完成',
      4: '已取消'
    },
    showPayButton: false
  },

  onLoad(options) {
    const { id, refresh } = options;
    
    if (!id) {
      wx.showToast({
        title: '订单ID不能为空',
        icon: 'none'
      });
      
      setTimeout(() => {
        wx.navigateBack();
      }, 1500);
      
      return;
    }
    
    this.setData({ orderId: id });
    this.loadOrderDetail();
    
    // 如果是支付完成后跳转回来，延迟1秒刷新订单详情确保获取最新状态
    if (refresh === '1') {
      setTimeout(() => {
        this.loadOrderDetail();
      }, 1000);
    }
  },
  
  // 加载订单详情
  loadOrderDetail() {
    this.setData({ loading: true });
    
    const url = config.API.ORDER.DETAIL + this.data.orderId;
    
    api.get(url)
      .then(res => {
        console.log('获取订单详情成功:', res);
        
        if (res.code === 200 || res.code === 0) {
          this.setData({
            orderInfo: res.data,
            loading: false,
            showPayButton: res.data.status === 0 // 0表示待支付
          });
        } else {
          wx.showToast({
            title: res.message || '获取订单失败',
            icon: 'none'
          });
          
          setTimeout(() => {
            wx.navigateBack();
          }, 1500);
        }
      })
      .catch(err => {
        console.error('获取订单详情失败:', err);
        
        wx.showToast({
          title: '获取订单失败，请重试',
          icon: 'none'
        });
        
        this.setData({ loading: false });
      });
  },
  
  // 取消订单
  cancelOrder() {
    wx.showModal({
      title: '提示',
      content: '确定要取消该订单吗？',
      success: (res) => {
        if (res.confirm) {
          wx.showLoading({
            title: '取消中...',
            mask: true
          });
          
          const url = config.API.ORDER.CANCEL.replace(':id', this.data.orderId);
          
          api.put(url)
            .then(res => {
              wx.hideLoading();
              
              if (res.code === 200) {
                wx.showToast({
                  title: '订单已取消',
                  icon: 'success'
                });
                
                // 重新加载订单详情
                this.loadOrderDetail();
              } else {
                wx.showToast({
                  title: res.message || '取消订单失败',
                  icon: 'none'
                });
              }
            })
            .catch(err => {
              wx.hideLoading();
              console.error('取消订单失败:', err);
              wx.showToast({
                title: '取消订单失败，请重试',
                icon: 'none'
              });
            });
        }
      }
    });
  },
  
  // 去支付
  goPay() {
    const { orderId } = this.data;
    wx.navigateTo({
      url: `/pages/order/payment/index?id=${orderId}`
    });
  },
  
  // 确认收货
  confirmReceipt() {
    wx.showModal({
      title: '提示',
      content: '确认已收到商品？',
      success: (res) => {
        if (res.confirm) {
          wx.showLoading({
            title: '处理中...',
            mask: true
          });
          
          const url = config.API.ORDER.RECEIVE.replace(':id', this.data.orderId);
          
          api.put(url)
            .then(res => {
              wx.hideLoading();
              
              if (res.code === 200) {
                wx.showToast({
                  title: '确认收货成功',
                  icon: 'success'
                });
                
                // 重新加载订单详情
                this.loadOrderDetail();
              } else {
                wx.showToast({
                  title: res.message || '确认收货失败',
                  icon: 'none'
                });
              }
            })
            .catch(err => {
              wx.hideLoading();
              console.error('确认收货失败:', err);
              wx.showToast({
                title: '确认收货失败，请重试',
                icon: 'none'
              });
            });
        }
      }
    });
  },
  
  // 查看物流
  viewLogistics() {
    const { orderId } = this.data;
    wx.showToast({
      title: '物流查询功能开发中',
      icon: 'none'
    });
    
    // 实际项目中跳转到物流查询页面
    // wx.navigateTo({
    //   url: `/pages/order/logistics/index?id=${orderId}`
    // });
  },
  
  // 复制订单号
  copyOrderNo() {
    const { orderInfo } = this.data;
    
    if (!orderInfo || !orderInfo.orderNo) {
      return;
    }
    
    wx.setClipboardData({
      data: orderInfo.orderNo,
      success: () => {
        wx.showToast({
          title: '订单号已复制',
          icon: 'success'
        });
      }
    });
  },
  
  // 图片加载错误处理
  onImageError(e) {
    const index = e.currentTarget.dataset.index;
    const orderInfo = this.data.orderInfo;
    
    if (orderInfo && orderInfo.items && orderInfo.items[index]) {
      orderInfo.items[index].cover = '/static/images/default-product.png';
      this.setData({ orderInfo });
    }
  }
}) 